#include "texteditor.h"
#include "tabledialog.h"
#include <QTextDocument>
#include <QTextBlock>
#include <QMessageBox>
#include <QImage>
#include <QPixmap>
#include <QTextDocumentFragment>
#include <QImageReader>
#include <QFileDialog>
#include <QDebug>
#include <QHBoxLayout>
#include <QPushButton>

TextEditor::TextEditor(QWidget *parent)
    : QWidget(parent)
{
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 创建工具栏
    toolBar = new QToolBar("格式工具栏", this);

    // 左对齐按钮
    leftAlignAction = toolBar->addAction("左对齐");
    leftAlignAction->setIcon(QIcon::fromTheme("format-justify-left"));
    connect(leftAlignAction, &QAction::triggered, this, &TextEditor::alignLeft);

    // 居中对齐按钮
    centerAlignAction = toolBar->addAction("居中对齐");
    centerAlignAction->setIcon(QIcon::fromTheme("format-justify-center"));
    connect(centerAlignAction, &QAction::triggered, this, &TextEditor::alignCenter);

    // 右对齐按钮
    rightAlignAction = toolBar->addAction("右对齐");
    rightAlignAction->setIcon(QIcon::fromTheme("format-justify-right"));
    connect(rightAlignAction, &QAction::triggered, this, &TextEditor::alignRight);

    // 分隔符
    toolBar->addSeparator();

    // 插入图片按钮
    insertImageAction = toolBar->addAction("插入图片");
    insertImageAction->setIcon(QIcon::fromTheme("insert-image"));
    connect(insertImageAction, &QAction::triggered, this, &TextEditor::insertImage);

    // 插入表格按钮
    insertTableAction = toolBar->addAction("插入表格");
    insertTableAction->setIcon(QIcon::fromTheme("insert-table"));
    connect(insertTableAction, &QAction::triggered, this, &TextEditor::insertTable);

    // 创建表格调整控件
    setupTableResizeControls();
    toolBar->addWidget(tableResizeWidget);

    // 创建支持图片缩放的文本编辑器
    textEdit = new ResizableImageTextEdit(this);

    // 连接文本光标位置变化信号，用于更新表格调整控件状态
    connect(textEdit, &QTextEdit::cursorPositionChanged, this, &TextEditor::updateTableResizeControls);

    // 将工具栏和文本编辑器添加到布局
    mainLayout->addWidget(toolBar);
    mainLayout->addWidget(textEdit);

    // 设置布局到主窗口
    setLayout(mainLayout);

    // 设置合理的初始大小
    resize(800, 600);

    // 设置窗口标题
    setWindowTitle("富文本编辑器");

    // 初始状态下禁用表格调整控件
    updateTableResizeControls();
}

TextEditor::~TextEditor()
{
}

void TextEditor::setupTableResizeControls()
{
    // 创建表格调整控件容器
    tableResizeWidget = new QWidget(this);
    QHBoxLayout *layout = new QHBoxLayout(tableResizeWidget);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(5);

    // 列宽控件
    columnWidthLabel = new QLabel("列宽:", tableResizeWidget);
    columnWidthSpinBox = new QSpinBox(tableResizeWidget);
    columnWidthSpinBox->setRange(10, 1000);
    columnWidthSpinBox->setValue(100);
    columnWidthSpinBox->setSuffix(" px");
    // 连接值改变的信号
    connect(columnWidthSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &TextEditor::applyTableResize);

    // 行高控件
    rowHeightLabel = new QLabel("行高:", tableResizeWidget);
    rowHeightSpinBox = new QSpinBox(tableResizeWidget);
    rowHeightSpinBox->setRange(10, 1000);
    rowHeightSpinBox->setValue(30);
    rowHeightSpinBox->setSuffix(" px");
    // 连接值改变的信号
    connect(rowHeightSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &TextEditor::applyTableResize);

    // 移除应用按钮
    // applyResizeButton = new QPushButton("应用", tableResizeWidget);
    // connect(applyResizeButton, &QPushButton::clicked, this, &TextEditor::applyTableResize);

    // 添加控件到布局
    layout->addWidget(columnWidthLabel);
    layout->addWidget(columnWidthSpinBox);
    layout->addWidget(rowHeightLabel);
    layout->addWidget(rowHeightSpinBox);
    // layout->addWidget(applyResizeButton);

    tableResizeWidget->setLayout(layout);
}

void TextEditor::updateTableResizeControls()
{
    // 检查当前是否在表格内
    bool inTable = (getSelectedTable() != nullptr);

    // 启用或禁用表格调整控件
    columnWidthLabel->setEnabled(inTable);
    columnWidthSpinBox->setEnabled(inTable);
    rowHeightLabel->setEnabled(inTable);
    rowHeightSpinBox->setEnabled(inTable);
    // applyResizeButton->setEnabled(inTable);
}

void TextEditor::alignLeft()
{
    textEdit->setAlignment(Qt::AlignLeft);
}

void TextEditor::alignCenter()
{
    textEdit->setAlignment(Qt::AlignCenter);
}

void TextEditor::alignRight()
{
    textEdit->setAlignment(Qt::AlignRight);
}

void TextEditor::insertImage()
{
    // 打开文件对话框选择图片
    QString filePath = QFileDialog::getOpenFileName(this,
        "选择图片", "", "图片文件 (*.png *.jpg *.jpeg *.bmp *.gif)");

    if (!filePath.isEmpty()) {
        QImage image(filePath);
        if (image.isNull()) {
            QMessageBox::warning(this, "错误", "无法加载图片！");
            return;
        }

        // 自动换行后插入图片
        QTextCursor cursor = textEdit->textCursor();
        cursor.insertBlock();

        // 创建图片格式并设置大小
        QTextImageFormat imageFormat;
        imageFormat.setName(filePath);

        // 设置初始图片大小，但最大宽度不超过编辑器宽度的70%
        int maxWidth = textEdit->width() * 0.7;
        if (image.width() > maxWidth) {
            double ratio = (double)maxWidth / image.width();
            imageFormat.setWidth(maxWidth);
            imageFormat.setHeight(image.height() * ratio);
        } else {
            imageFormat.setWidth(image.width());
            imageFormat.setHeight(image.height());
        }

        // 插入图片
        cursor.insertImage(imageFormat);
        cursor.insertBlock();
    }
}

void TextEditor::insertTable()
{
    TableDialog dialog(this);
    if (dialog.exec() == QDialog::Accepted) {
        int rows = dialog.rows();
        int columns = dialog.columns();

        QTextCursor cursor = textEdit->textCursor();

        // 在表格前自动换行
        cursor.insertBlock();

        // 设置对齐方式为靠左
        QTextBlockFormat blockFormat;
        blockFormat.setAlignment(Qt::AlignLeft);
        cursor.setBlockFormat(blockFormat);

        // 插入表格并设置格式
        QTextTableFormat tableFormat;
        tableFormat.setBorder(1);
        tableFormat.setCellPadding(5);
        tableFormat.setCellSpacing(0);
        tableFormat.setAlignment(Qt::AlignLeft);
        tableFormat.setProperty(QTextFormat::TableCellSpacing, 0);

        // 设置等宽列
        QVector<QTextLength> columnWidths;
        for (int i = 0; i < columns; i++) {
            columnWidths.append(QTextLength(QTextLength::FixedLength, 100));
        }
        tableFormat.setColumnWidthConstraints(columnWidths);

        QTextTable *table = cursor.insertTable(rows, columns, tableFormat);

        // 默认行高
        int defaultRowHeight = 30;

        // 设置每个单元格的格式和内容
        for (int row = 0; row < rows; ++row) {
            for (int col = 0; col < columns; ++col) {
                QTextTableCell cell = table->cellAt(row, col);

                // 设置单元格格式
                QTextTableCellFormat cellFormat = cell.format().toTableCellFormat();
                cellFormat.setPadding(5);
                cell.setFormat(cellFormat);

                // 设置块格式
                QTextCursor cellCursor = cell.firstCursorPosition();
                QTextBlockFormat cellBlockFormat;
                cellBlockFormat.setAlignment(Qt::AlignVCenter | Qt::AlignLeft); // 垂直居中，水平靠左
                cellBlockFormat.setLineHeight(defaultRowHeight, QTextBlockFormat::FixedHeight);

                cellCursor.setBlockFormat(cellBlockFormat);
            }
        }

        // 在表格后自动换行
        cursor = table->cellAt(rows-1, columns-1).lastCursorPosition();
        cursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor);
        cursor.insertBlock();
        textEdit->setTextCursor(cursor);

        // 更新控件状态
        updateTableResizeControls();
    }
}

void TextEditor::applyTableResize()
{
    QTextTable *table = getSelectedTable();

    if (table) {
        int currentRow = getCurrentTableRow();
        int currentCol = getCurrentTableColumn();

        if (currentRow != -1 && currentCol != -1) {
            // 记住当前光标位置
            QTextCursor originalCursor = textEdit->textCursor();

            // 1. 应用列宽
            int columnWidth = columnWidthSpinBox->value();
            QTextTableFormat tableFormat = table->format();

            QVector<QTextLength> columnWidths;
            if (tableFormat.hasProperty(QTextFormat::TableColumnWidthConstraints)) {
                columnWidths = tableFormat.columnWidthConstraints();
            } else {
                for (int i = 0; i < table->columns(); ++i) {
                    columnWidths.append(QTextLength(QTextLength::PercentageLength, 100.0 / table->columns()));
                }
            }

            // 更新选中列的宽度
            columnWidths[currentCol] = QTextLength(QTextLength::FixedLength, columnWidth);
            tableFormat.setColumnWidthConstraints(columnWidths);

            // 应用新的表格格式
            table->setFormat(tableFormat);

            // 2. 应用行高 - 使用单元格属性而不是文本块属性
            int rowHeight = rowHeightSpinBox->value();

            // 取得当前行的所有单元格
            for (int col = 0; col < table->columns(); ++col) {
                QTextTableCell cell = table->cellAt(currentRow, col);

                // 设置单元格格式
                QTextTableCellFormat cellFormat = cell.format().toTableCellFormat();

                // 计算单元格内容的实际高度
                int contentHeight = calculateCellContentHeight(cell);

                // 计算底部填充，使文字保持在顶部
                // 顶部使用固定小的填充
                int topPadding = 2; // 使用小的顶部填充
                int bottomPadding = rowHeight - contentHeight - topPadding;

                // 如果底部填充计算结果为负，表示内容超出了设定行高，则使用最小填充
                if (bottomPadding < 0) bottomPadding = 0;

                // 设置填充值
                cellFormat.setTopPadding(topPadding);
                cellFormat.setBottomPadding(bottomPadding);
                cellFormat.setLeftPadding(5);
                cellFormat.setRightPadding(5);

                // 应用格式
                cell.setFormat(cellFormat);

                // 确保文本块没有任何垂直对齐设置
                QTextCursor cellCursor = cell.firstCursorPosition();
                QTextBlock block = cellCursor.block();
                while (block.position() < cell.lastPosition() && block.isValid()) {
                    QTextCursor blockCursor(block);
                    QTextBlockFormat blockFormat = block.blockFormat();

                    // 移除所有的行高设置
                    blockFormat.setLineHeight(0, QTextBlockFormat::SingleHeight);

                    // 设置左对齐
                    blockFormat.setAlignment(Qt::AlignLeft | Qt::AlignTop);

                    blockCursor.setBlockFormat(blockFormat);
                    block = block.next();
                }
            }

            // 恢复原始光标位置
            textEdit->setTextCursor(originalCursor);
        }
    }
}

// 新增辅助方法来计算单元格内容的实际高度
int TextEditor::calculateCellContentHeight(const QTextTableCell &cell)
{
    // 获取单元格内容
    QTextCursor cellCursor = cell.firstCursorPosition();
    cellCursor.setPosition(cell.lastPosition(), QTextCursor::KeepAnchor);

    // 获取所有文本块
    int totalHeight = 0;
    QTextBlock block = cellCursor.document()->findBlock(cell.firstPosition());
    QTextBlock end = cellCursor.document()->findBlock(cell.lastPosition()).next();

    while (block != end && block.isValid()) {
        QTextLayout *layout = block.layout();
        // 获取块中所有行的高度总和
        int blockHeight = 0;
        for (int i = 0; i < layout->lineCount(); ++i) {
            QTextLine line = layout->lineAt(i);
            blockHeight += line.height();
        }

        // 如果没有行或高度为0，使用默认行高
        if (blockHeight == 0 && !block.text().isEmpty()) {
            blockHeight = QFontMetrics(block.charFormat().font()).height();
        }

        totalHeight += blockHeight;
        block = block.next();
    }

    // 确保最小高度
    if (totalHeight < QFontMetrics(QFont()).height()) {
        totalHeight = QFontMetrics(QFont()).height();
    }

    return totalHeight;
}

int TextEditor::getCurrentTableRow()
{
    QTextTable *table = getSelectedTable();
    if (!table) return -1;

    QTextCursor cursor = textEdit->textCursor();

    // 获取当前光标所在的单元格
    for (int row = 0; row < table->rows(); ++row) {
        for (int col = 0; col < table->columns(); ++col) {
            QTextTableCell cell = table->cellAt(row, col);
            int cellStartPos = cell.firstPosition();
            int cellEndPos = cell.lastPosition();

            // 检查光标是否在当前单元格内
            if (cursor.position() >= cellStartPos && cursor.position() <= cellEndPos) {
                return row;
            }
        }
    }

    return -1;
}

int TextEditor::getCurrentTableColumn()
{
    QTextTable *table = getSelectedTable();
    if (!table) return -1;

    QTextCursor cursor = textEdit->textCursor();

    // 获取当前光标所在的单元格
    for (int row = 0; row < table->rows(); ++row) {
        for (int col = 0; col < table->columns(); ++col) {
            QTextTableCell cell = table->cellAt(row, col);
            int cellStartPos = cell.firstPosition();
            int cellEndPos = cell.lastPosition();

            // 检查光标是否在当前单元格内
            if (cursor.position() >= cellStartPos && cursor.position() <= cellEndPos) {
                return col;
            }
        }
    }

    return -1;
}

QTextTable *TextEditor::getSelectedTable()
{
    QTextCursor cursor = textEdit->textCursor();
    return cursor.currentTable();
}
